<template>
	<view class="content">
		<!-- 轮播图 -->
		<swiper class="swiper" indicator-dots autoplay interval="3000" duration="500">
			<swiper-item v-for="(item, index) in goodsDetail.pictureIntegrationDtoS" :key="index">
				<image style="width: 100%;height: 100%;" :src="item.pictureUrl" mode="aspectFill"></image>
			</swiper-item>
		</swiper>

		<!-- 商品信息 -->
		<view class="product-info">
			<view style="width: 100%;">
				<text class="sellingPrice">¥{{ selectedSpecsPrice }}</text>
				<text class="originalCost">¥{{ selectedOriginalCost }}</text>
			</view>
			<view class="num">库存{{goodsDetail.commodityInventory}}</view>
			<view class="num">已售{{goodsDetail.virtualSales}}</view>
			<view class="name">{{goodsDetail.commodityName}}</view>
		</view>

		<!-- 规格和评价选项 -->
		<view class="specificationsBox" @click="togglePopup('buyNow')"> <!-- 注意这里 -->
			<view class="leftText">请选择规格</view>
			<view class="rightIcon"><text class="iconfont icon-xiangyou">></text></view>
		</view>
		<view class="specificationsBox" @click="goEvaluate">
			<view class="leftText">评价（{{evaluateTotal}}）</view>
			<view class="rightIcon" style="float: right;display: block;"><text class="iconfont icon-xiangyou">></text>
			</view>
		</view>
		<view class="evaluation-item" v-for="(item, index) in evaluateList" :key="index">
			<!-- 左侧：头像 -->
			<view class="avatar-container">
				<image :src="item.user.headPortrait" class="avatar"></image>
			</view>
			<!-- 右侧：评价内容 -->
			<view class="content-container">
				<!-- 昵称 -->
				<view class="nickname">{{ item.user.nickName }}</view>
				<!-- 评价内容，限制为两行 -->
				<view class="evaluation-content">
					{{ item.evaluationContent !== undefined && item.evaluationContent !== null ? item.evaluationContent : '此用户觉得商品很好，给出评论'}}
				</view>
				<!-- 图片展示，最多显示三张 -->
				<view class="images-container">
					<image v-for="(pic, picIndex) in getVisiblePictures(item)" :key="picIndex" :src="pic.pictureUrl"
						class="evaluation-image" mode="aspectFill">
					</image>
				</view>
			</view>
		</view>
		<!-- 商品详情 -->
		<view class="inform">
			<p class="title">——商品详情——</p>
			<div class="content-container">
				<p v-html="formattedDetails"></p>
			</div>
		</view>

		<!-- 底部导航栏 -->
		<view class="fixed-bottom" v-if="!isPopupVisible">
			<uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick"
				@buttonClick="buttonClick" />
		</view>

		<!-- 规格弹窗 -->
		<uni-popup ref="popup" :mask-click="false" :before-close="true" type="bottom" style="padding-bottom:0">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">请选择规格</text>
					<text class="popup-close" @click="closePopup">×</text>
				</view>
				<view class="popup-product-info">
					<image :src="selectedSpecsImage" class="popup-product-image" mode="aspectFill"></image>
					<view class="popup-product-details">
						<p class="popup-name">{{ goodsDetail.commodityName }}</p>
						<p class="popup-price">¥{{ selectedSpecsPrice }}</p>
					</view>
				</view>
				<!-- 动态规格选择 -->
				<view v-if="availableSpecifications.length > 0">
					<text
						class="spec-title">{{goodsDetail.commoditySpecificationBasicInformationDtoS[0].attributeName}}</text>
					<view class="picker-container">
						<view v-for="(spec, index) in availableSpecifications" :key="index" class="picker-item"
							:class="{ 'selected': selectedIndex === index }" @click="updateSelectedSpec(index)">
							{{ spec.attributeValue }}
						</view>
					</view>
					<text
						v-if="goodsDetail.commoditySpecificationBasicInformationDtoS[0].commoditySpecificationAttributeInfoDtoS[0].specificationName"
						class="spec-title">{{goodsDetail.commoditySpecificationBasicInformationDtoS[0].commoditySpecificationAttributeInfoDtoS[0].specificationName}}</text>
					<view class="picker-container"
						v-if="goodsDetail.commoditySpecificationBasicInformationDtoS[0].commoditySpecificationAttributeInfoDtoS[0].specificationName">
						<view v-for="(value, idx) in selectedSpecsValues" :key="idx" class="picker-item"
							:class="{ 'selected': selectedSpecValueIndex === idx }"
							@click="updateSelectedSpecValue(idx)">
							{{ value.specificationValue }}
						</view>
					</view>
				</view>
				<!-- 数量选择 -->
				<view class="quantity-selector">
					<p class="title">数量</p>
					<view class="button" @click="decreaseQuantity">-</view>
					<input type="number" v-model.number="selectedQuantity" min="1" />
					<view class="button" @click="increaseQuantity">+</view>
				</view>
				<!-- 按钮 -->
				<view class="popup-buttons">
					<button v-if="popupButtonType === 'addCart'" class="popup-button" @click="addCart()">加入购物车</button>
					<button v-if="popupButtonType === 'buyNow'" class="popup-button" @click="buyNow()">立即购买</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getGoodsDetail,
		addCollect,
		delCollect,
		getEvaluate
	} from '@/api/goods.js';
	import {
		addShopping
	} from '@/api/order.js';
	import {
		getUserInfo
	} from '@/api/user.js';
	export default {
		data() {
			return {
				options: [{
						icon: 'shop',
						text: '客服'
					},
					{
						icon: 'star',
						text: '收藏'
					}
				],
				buttonGroup: [{
						text: '加入购物车',
						backgroundColor: '#ff0000',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: '#ffa200',
						color: '#fff'
					}
				],
				goodsDetail: {},
				selectedIndex: 0,
				selectedSpecValueIndex: 0,
				isPopupVisible: false,
				popupButtonType: 'buyNow',
				selectedSpecId: null, // 用于存储选中的一级规格ID
				selectedSpecValueId: null, // 用于存储选中的二级规格ID
				selectedQuantity: 1, // 默认选择数量为1
				userInfo: {},
				goodsId: '',
				evaluateList: [],
				evaluateTotal: ''
			};
		},
		computed: {
			availableSpecifications() {
				// 获取一级规格列表
				return this.goodsDetail.commoditySpecificationBasicInformationDtoS || [];
			},
			selectedSpecsValues() {
				// 根据选中的一级规格，获取对应的二级规格列表
				const currentSpec = this.availableSpecifications[this.selectedIndex];
				return currentSpec?.commoditySpecificationAttributeInfoDtoS || [];
			},
			selectedSpecsImage() {
				// 获取选中的规格对应的图片
				const selectedSpec = this.selectedSpecsValues[this.selectedSpecValueIndex];
				return selectedSpec?.specificationPicture || '';
			},
			selectedSpecsPrice() {
				// 获取选中的规格对应的价格
				const selectedSpec = this.selectedSpecsValues[this.selectedSpecValueIndex];
				return selectedSpec ? selectedSpec.sellingPrice : '无';
			},
			selectedOriginalCost() {
				// 获取选中的规格对应的原价
				const selectedSpec = this.selectedSpecsValues[this.selectedSpecValueIndex];
				return selectedSpec ? selectedSpec.originalCost : '无';
			},
			formattedDetails() {
				if (this.goodsDetail.commodityDetails) {
					return this.goodsDetail.commodityDetails.replace(/\<img/g, '<img style="max-width:100%;height:auto"');
				}
				return '';
			},
		},
		watch: {
			'goodsDetail.commoditySpecificationBasicInformationDtoS': {
				handler(newVal) {
					console.log('商品规格更新:', newVal);
					this.setDefaultSelectedSpecs();
				},
				deep: true // 确保监听到对象内部的变化
			}
		},
		onShareAppMessage: function() {
			return {
				title: '骨宁堂',
			}
		},
		onShareTimeline: function() {
			return {
				title: '骨宁堂',
			}
		},
		onLoad(option) {
			this.goodsId = option.id
			this.getUser()
			this.getDetail(option.id);
			this.getEvaluateList()
		},
		methods: {
			// 获取可见的图片数组，最多返回三个元素
			getVisiblePictures(item) {
				return item.pictureIntegrations.slice(0, 3);
			},
			//获取评论
			getEvaluateList() {
				const data = {
					pageNumber: 1,
					pageSize: 10,
					commodityId: this.goodsId,
				};
				getEvaluate(data).then(res => {
					this.evaluateList = res.data.records.slice(0, 3)
					this.evaluateTotal = res.data.total
				})
			},

			//获取用户信息
			getUser() {
				getUserInfo().then(res => {
					this.userInfo = res.data
				});
			},
			//打开规格弹窗
			buttonClick(e) {
				if (e.content.text == '加入购物车') {
					this.popupButtonType = 'addCart';
				} else {
					this.popupButtonType = 'buyNow';
				}
				this.$refs.popup.open();
				this.isPopupVisible = true;
			},
			onClick(e) {
				if (e.content.text == '收藏') {
					const params = {
						commodityId: this.goodsDetail.id,
						specificationId: this.selectedSpecValueId,
						userId: this.userInfo.id
					};
					console.log(this.goodsDetail)
					if (this.goodsDetail.isCollect == 0) {
						addCollect(params).then(res => {
							uni.showToast({
								icon: "none",
								title: '收藏成功'
							});
							this.getDetail(this.goodsId)
						})
					} else if (this.goodsDetail.isCollect == 1) {
						delCollect(params).then(res => {
							uni.showToast({
								icon: "none",
								title: '取消成功'
							});
							this.getDetail(this.goodsId)
						})
					}
				} else {
					uni.showToast({
						icon: "none",
						title: '正在开发'
					});
				}
			},
			//获取商品详情
			getDetail(id) {
				getGoodsDetail(id).then(res => {
					if (res.data.isCollect == 0) {
						this.options[1].icon = 'star'
					} else if (res.data.isCollect == 1) {
						this.options[1].icon = 'star-filled'
					}
					this.goodsDetail = res.data;
					this.goodsDetail.virtualSales=res.data.virtualSales+res.data.commoditySalesVolume
					console.log('商品详情加载完成:', this.goodsDetail);
					this.setDefaultSelectedSpecs(); // 立即设置默认选中的规格
				});
			},
			//去评论
			goEvaluate() {
				uni.navigateTo({
					url: '/pages/classification/evaluateDetail/index?id=' + this.goodsDetail.id
				})
			},
			// 打开规格弹窗
			togglePopup(buttonType = 'buyNow') {
				this.popupButtonType = buttonType;
				this.isPopupVisible = true;
				if (this.isPopupVisible) {
					this.$refs.popup.open();
				}
			},
			//关闭规格弹窗
			closePopup() {
				this.isPopupVisible = false;
				this.$refs.popup.close();
			},
			//点击一级规格
			updateSelectedSpec(index) {
				this.selectedIndex = index;
				this.selectedSpecValueIndex = 0; // 切换一级规格时重置二级规格选择

				const selectedSpec = this.availableSpecifications[index];
				this.selectedSpecId = selectedSpec.id; // 假设规格对象有一个id字段
				console.log('选中了一级规格:', selectedSpec);
			},
			//点击二级规格
			updateSelectedSpecValue(idx) {
				this.selectedSpecValueIndex = idx;
				const selectedSpecValue = this.selectedSpecsValues[idx];
				this.selectedSpecValueId = selectedSpecValue.id; // 假设规格值对象有一个id字段
				console.log('选中了二级规格:', selectedSpecValue);
			},
			//设置默认选中的规格
			setDefaultSelectedSpecs() {
				if (this.availableSpecifications.length > 0) {
					const defaultSpec = this.availableSpecifications[0];
					this.selectedIndex = 0;
					this.selectedSpecId = defaultSpec.id; // 设置一级规格ID

					if (defaultSpec.commoditySpecificationAttributeInfoDtoS && defaultSpec
						.commoditySpecificationAttributeInfoDtoS.length > 0) {
						const defaultValue = defaultSpec.commoditySpecificationAttributeInfoDtoS[0];
						this.selectedSpecValueIndex = 0;
						this.selectedSpecValueId = defaultValue.id; // 设置二级规格ID
					}
				}
			},
			//数量加减
			decreaseQuantity() {
				if (this.selectedQuantity > 1) {
					this.selectedQuantity--;
				}
			},
			increaseQuantity() {
				this.selectedQuantity++;
			},
			//加入购物车
			addCart() {
				// console.log('加入购物车', `规格ID: ${this.selectedSpecId}, 规格值ID: ${this.selectedSpecValueId}`);
				const data = {
					userId: this.userInfo.id,
					commodityId: this.goodsDetail.id,
					specificationId: this.selectedSpecValueId,
					count: this.selectedQuantity // 使用用户选择的数量
				};
				addShopping(data).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: '添加成功',
							icon: 'none'
						});
					}
					this.isPopupVisible = false;
					console.log('购物车添加结果:', res);
				});
			},
			//下单
			buyNow() {
				// 处理立即购买逻辑，使用this.selectedSpecId 和 this.selectedSpecValueId
				console.log('立即购买', `规格ID: ${this.selectedSpecId}, 规格值ID: ${this.selectedSpecValueId}`);
				// 拼接两个规格ID，并执行立即购买的具体业务逻辑，如导航至订单确认页面等
				uni.navigateTo({
					url: `/pages/classification/addOrder/index?goodsId=${this.goodsDetail.id}&specId=${this.selectedSpecId}&specValueId=${this.selectedSpecValueId}&count=${this.selectedQuantity}&type=${'商品'}`
				})
			}
		}
	};
</script>
<style lang="scss">
	@import '@/uni.scss'; // 导入全局 SCSS 变量文件

	.content {
		background-color: $uni-bg-color-grey;
		padding-bottom: 200rpx;
	}

	.swiper {
		height: 400px;
	}

	.product-info {
		margin: 20rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		background-color: $uni-bg-color-white;
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;

		.sellingPrice {
			color: $uni-color-orange;
			font-size: 26px;
		}

		.originalCost {
			color: $uni-text-color-grey;
			font-size: 18px;
			text-decoration: line-through;
		}

		.num {
			font-size: 14px;
			color: $uni-text-color-grey;
			background-color: $uni-bg-color-grey;
			align-self: flex-end;
			margin: 10rpx 20rpx 10rpx 0rpx;
			padding: 4rpx;
		}

		.name {
			width: 100%;
			font-size: 20px;
			font-weight: bold;
		}
	}

	.specificationsBox {
		padding: 30rpx 20rpx;
		margin: 20rpx;
		border-radius: 20rpx;
		font-size: 26rpx;
		background-color: $uni-bg-color-white;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.inform {
		margin-top: 20rpx;

		.title {
			margin: 20rpx 0rpx;
			color: $uni-text-color-grey;
			text-align: center;
		}
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: white;
		padding: 10px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	}

	.content-container p {
		word-wrap: break-word;
		overflow-wrap: break-word;
		white-space: pre-line;
	}




	.popup-content {
		height: 1100rpx;
		background: #fff;
		padding: 20rpx;
		margin-bottom: -60rpx;
		border-radius: 20rpx;

		.popup-header {
			height: 40rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20px;
			border: 2rpx soldi pink;

			.popup-title {
				font-size: 16px;
			}

			.popup-close {
				font-size: 24px;
				cursor: pointer;
			}
		}

		.popup-product-info {
			width: 100%;
			display: flex;
			align-items: center;
			margin-bottom: 20px;
		}

		.popup-product-image {
			width: 180rpx;
			height: 180rpx;
			margin-right: 20rpx;
			border-radius: 20rpx;
		}

		.popup-product-details {
			height: 180rpx;
		}

		.popup-name {
			height: 120rpx;
			font-size: 38rpx;
		}

		.popup-price {
			height: 60rpx;
			font-size: 38rpx;
			font-weight: bold;
			color: $uni-color-orange;
		}

		.spec-title {
			display: block;
			font-size: 32rpx;
			font-weight: bold;
			line-height: 80rpx;
		}

		.spec-selection {
			margin-bottom: 20rpx;
		}

		.picker-container {
			display: flex;
			flex-wrap: wrap;
		}

		.picker-item {
			margin: 5rpx;
			height: 40rpx;
			padding: 10rpx 40rpx;
			border-radius: 40rpx;
			// border: 1px solid $uni-border-color;
			background-color: $uni-bg-color-grey;
			cursor: pointer;
			transition: background-color 0.3s;

			&.selected {
				border: 2rpx solid $uni-color-orange;
				background-color: #fbfaee;
				color: $uni-color-orange;
			}
		}

		.quantity-selector {
			width: 100%;
			height: 80rpx;
			display: flex;

			.title {
				width: 70%;
				font-size: 32rpx;
				font-weight: bold;
				line-height: 80rpx;
			}

			input {
				width: 80rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				margin: 10rpx 0rpx;
			}

			.button {
				width: 60rpx;
				height: 60rpx;
				text-align: center;
				line-height: 60rpx;
				background-color: $uni-bg-color-grey;
				border-radius: 6rpx;
				margin: 10rpx 0rpx;
			}
		}

		.popup-buttons {
			margin-top: 20rpx;

			button {
				flex: 1;
				margin: 20rpx;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 80rpx;
				background-color: $uni-color-orange;
				color: $uni-text-color-inverse;
				text-align: center;
			}
		}
	}

	.evaluation-item {
		display: flex;
		margin: 10px;
		background-color: #fff;
		margin-top: -20rpx;
		padding: 20rpx;
	}

	.avatar-container {
		flex: 0 0 auto;
		margin-right: 20rpx;
	}

	.avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
	}

	.content-container {
		flex: 1 1 auto;
	}

	.nickname {
		font-weight: bold;
		font-size: 28rpx;
	}

	.evaluation-content {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		font-size: 28rpx;
		color: $uni-text-color-grey6;
	}

	.images-container {
		display: flex;
		flex-wrap: nowrap;
		overflow: hidden;
		margin-top: 10rpx;
		/* 根据需要调整 */
	}

	.evaluation-image {
		width: 160rpx;
		height: 160rpx;
		margin-right: 10rpx;
		flex-shrink: 0;
	}
</style>